#include "Renderer.h"
#include "Material.h"
using namespace std;
Renderer::Renderer(IDirect3DDevice9 *device)
	:device(device)
{
}

void Renderer::Draw( vector<RenderOperation> rops )
{
	vector<RenderOperation>::iterator i;
	
	device->BeginScene();

	for( i = rops.begin(); i != rops.end(); ++i )
	{
		
		//set geoumetry		
		device->SetVertexDeclaration( (*i).vdecl );
		device->SetStreamSource(0, (*i).vb, 0, (*i).vertexStride);
		device->SetIndices( (*i).ib );
		// configure material
		Material *mtrl = (*i).mtrl;
		if(mtrl != 0)
		{
			
			mtrl->UpdateShaderConsts();

			//set technique "main"
			D3DXHANDLE tech;
			tech = mtrl->GetEffect()->GetTechniqueByName("main");
			mtrl->GetEffect()->SetTechnique(tech);


			//begin shader passes
			UINT pass;
			mtrl->GetEffect()->Begin(&pass,0);
			for( size_t p = 0; p < pass; ++p )
			{
				mtrl->GetEffect()->BeginPass(p);
				device->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, (*i).vertexCount, 0, (*i).primCount );
				mtrl->GetEffect()->EndPass();
			}
			mtrl->GetEffect()->End();
		}
		else
		{
			device->SetTransform( D3DTS_WORLD, &(i->model) );
			device->SetTransform( D3DTS_VIEW, &(i->view ) );
			device->SetTransform( D3DTS_PROJECTION, &(i->proj) );

			device->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, (*i).vertexCount, 0, (*i).primCount );
		}
	}

	device->EndScene();
}